package com.shanzhu.hospital.config;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shanzhu.hospital.utils.JwtUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
//用于验证请求中的JWT令牌有效性
public class JwtInterceptor implements HandlerInterceptor {

    @Override  //在请求处理前进行拦截
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> map = new HashMap<>();
        //获取请求头中的令牌
        String token = request.getHeader("token");//从请求头中获取名为'token'的JWT令牌
        try {
            JwtUtil.verify(token);//验证令牌
            return true;
        } catch (SignatureVerificationException e) {//捕获不同类型的JWT验证异常
            e.printStackTrace();
            map.put("msg", "无效签名！");
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            map.put("msg", "token过期！");
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            map.put("msg", "token算法不一致！");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "token无效！");
        }
        map.put("state", false);//设置操作状态为false
        String json = new ObjectMapper().writeValueAsString(map);//将map转换为json字符串
        response.setContentType("application/json;charset=UTF-8");//设置响应内容类型
        response.getWriter().println(json);//将json写进响应体

        return false;
    }
}
